<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/9
 * Time: 18:32
 */
namespace app\admin\controller;
use think\Db;
use think\Request;

class Rule extends AdminController
{
    public function rule_list()
    {
        $data = Db::table("free_rule")
            ->field('id, name, category, rule')
            ->select();
        $roles = Db::table("free_role")->select();
        $this->assign('data', $data);
        $this->assign('roles', $roles);
        return $this->fetch('page/rule_list');
    }
    // 添加新的规则
    public function rule_add()
    {
        $name = $_POST['name'];
        $rule = $_POST['rules'];
        $roleId = $_POST['roleId'];
        $cname = 1;                     // 暂留字段, 用于权限分类

        $res1 = Db::table('free_rule')
            ->insert(['name' => $name, 'category' => $cname, 'rule' => $rule]);
        $lastId = Db::table('free_rule')->getLastInsID();

        $res2 = Db::table('free_role_rule')
            ->insert(['roid' => $roleId, 'ruid' => $lastId]);

        if ($res1 && $res2){
            $this->redirect(url('admin/Rule/rule_list'));
        }else{
            return '添加失败';
        }
    }

    // 修改规则界面
    public function rule_edit($id)
    {
        $rule = Db::name('rule')->find($id);
        $this->assign('rule', $rule);
        return $this->fetch('page/rule_edit');
    }

    // 修改规则
    public function update()
    {
        $res = Db::table('free_rule')
            ->where('id', $_POST['id'])
            ->update(['name' => $_POST['name'], 'rule' => $_POST['rule']]);

        if($res){
            return "修改成功";
        }else{
            return "修改失败";
        }
    }

    // 删除规则
    public function remove()
    {
        $res1 = Db::table('free_rule')
            ->where('id', $_GET['id'])
            ->delete();
        // 联动删除role_rule
        $res2 = Db::table('free_role_rule')
            ->where('ruid', $_GET['id'])
            ->delete();

        if ($res1 || $res2) {
            return true;
        }
        return false;
    }
}